package com.szty.libarytest.ble

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import com.szty.libarytest.R
import com.szty.libarytest.other.loge
import kotlinx.android.synthetic.main.activity_ble_scan.*

class BleScanActivity : AppCompatActivity() {
    private val data = arrayListOf<String>()
    private val btm by lazy {
        getSystemService(android.content.Context.BLUETOOTH_SERVICE) as BluetoothManager
    }
    private val bta by lazy {
        btm.adapter
    }
    private val mAdapter by lazy {
        ArrayAdapter<String>(this, R.layout.simple_list_item,R.id.tv_ble_address, data)
    }
    private var scanner: BluetoothLeScanner? = null
    private val scannerCallback = object : ScanCallback() {
        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            "onScanFailed".loge()

        }

        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            super.onScanResult(callbackType, result)
            "onScanResult".loge()
            if (result == null) return
            val device = result.device
            data.add("${device.address} ${device.name}")
            mAdapter.notifyDataSetChanged()
        }

        override fun onBatchScanResults(results: MutableList<ScanResult>?) {
            super.onBatchScanResults(results)
            "onBatchScanResults".loge()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ble_scan)
        initView()
    }

    private fun initView() {
        btn_start_scan.setOnClickListener {
            scanBle()
        }
        ble_list.apply {
            adapter = mAdapter

        }
    }

    private fun scanBle() {
        if (bta == null || !bta.isEnabled) {
            startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1)
        } else {
            scanner = bta.bluetoothLeScanner
            scanner!!.startScan(scannerCallback)
            ble_list.postDelayed({
                scanner!!.stopScan(scannerCallback)
            },1000*8)
        }
    }

}